package com.dty.dtycompute.differencesTable.controller;

import com.dty.common.utils.LogUtils;
import com.dty.dtycompute.differencesTable.domain.ParamEntity;
import com.dty.dtycompute.differencesTable.domain.TdataHtWq;
import com.dty.dtycompute.differencesTable.domain.TrptDayWq;
import com.dty.dtycompute.differencesTable.service.TdataHtWqService;
import com.dty.dtycompute.differencesTable.service.TrptDayWqService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * author: zouzhuo
 * Date: 2023/5/30 0030
 * Time: 下午 16:33
 **/
@RestController
@RequestMapping("/DifferenceDayCalc")
public class DifferenceDayCalcController {

    @Autowired
    private TdataHtWqService tdataHtWqService;
    @Autowired
    private TrptDayWqService trptDayWqService;

    //测试日计算
    @Scheduled(cron = "0 0/1 * * * ?")
    public void dayEq() {
        calcDayManual("2023-05-09", "2023-05-20", "101,102,103");
    }

    /**
     * 时间一天
     * 手动计算
     *
     * @param startTIme 起始时间
     * @param endTIme   截止时间
     * @param roomNos   房间号
     */
    @RequestMapping("/ManualCalc")
    public void calcDayManual(String startTIme, String endTIme, String roomNos) {

//        new Thread(() -> {
        LocalDate sdt = LocalDate.parse(startTIme, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(1);
        LocalDate edt = LocalDate.parse(endTIme, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        int i = 0;
        while (sdt.isBefore(edt)) {
            //没有传参数计算默认昨日与今日
            differenceDayCalc(sdt, roomNos);
            sdt = sdt.plusDays(1);
            i++;
        }
//        }).start();
    }

    @RequestMapping(value = "/dayWq")
    private void differenceDayCalc(LocalDate sdt, String roomNos) {

        if (sdt == null) {
            sdt = LocalDate.now().minusDays(1);
        }
        LogUtils.info("DayEqController", "开始计算【仪表日水量数据】【开始时间：" + LocalDate.now() + "】", "DayEqCompute");
        LogUtils.info("DayEqController", "【日报日期：" + sdt.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "】", "DayEqCompute");
        //将逗号分开的表号字符串
        if (StringUtils.isNotEmpty(roomNos)) {
            ParamEntity paramEntity = new ParamEntity();
            if (StringUtils.isNotEmpty(roomNos)) {
                String[] meterIdList = roomNos.split(",");
                StringBuilder roomNosBuilder = new StringBuilder();
                for (String me : meterIdList) {
                    roomNosBuilder.append("'").append(me).append("',");
                }
                roomNos = roomNosBuilder.toString();
                roomNos = roomNos.substring(0, roomNos.length() - 1);
            }
            paramEntity.setRoomNos(roomNos);
            //起始表码 进水采集时间与出水采集时间不超过4个小时算是一天的
            paramEntity.setStartTime(sdt.minusDays(1).toString());
            List<TdataHtWq> tdataHtWqStart = tdataHtWqService.selectHtWqListStart(paramEntity);
            //截止
            paramEntity.setStartTime(sdt.toString());
            List<TdataHtWq> tdataHtWqend = tdataHtWqService.selectHtWqListStart(paramEntity);
            Map<String, TdataHtWq> tdataHtWqendMap = tdataHtWqend.stream().collect(Collectors.toMap(TdataHtWq::getRoomId, Function.identity(), (oldValue, newValue) -> oldValue));

            for (TdataHtWq tdataHtWq : tdataHtWqStart) {
                //起始时间
                LocalDateTime inDt = tdataHtWq.getInDt();
                String startTime = inDt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                //截止表码
                TdataHtWq tdataHtWqEnd = tdataHtWqendMap.get(tdataHtWq.getRoomId());

                if (tdataHtWqEnd != null) {
                    //截止时间
                    LocalDateTime inDtEnd = tdataHtWqEnd.getInDt();
                    String endTime = inDtEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    //进水起始表码
                    BigDecimal inWmBmStart = tdataHtWq.getInWmBm();
                    //回水起始表码
                    BigDecimal outWmBmStart = tdataHtWq.getOutWmBm();
                    BigDecimal wq = tdataHtWq.getWq();
                    //隔天截止码
                    BigDecimal inWmBmEnd = tdataHtWqEnd.getInWmBm();
                    BigDecimal outWmBmEnd = tdataHtWqEnd.getOutWmBm();
                    //用水量今天
                    BigDecimal wqEnd = tdataHtWqEnd.getWq();

                    TrptDayWq trptDayWq = new TrptDayWq();
                    trptDayWq.setRoomId(tdataHtWq.getRoomId());
                    trptDayWq.setStrDay(sdt.toString());
                    //起始时间 昨天的供水时间（首）
                    trptDayWq.setSdt(startTime);
                    //截止时间 今天的供水时间（尾）
                    trptDayWq.setEdt(endTime);
                    trptDayWq.setSinBm(inWmBmStart);
                    trptDayWq.setEinBm(inWmBmEnd);
                    trptDayWq.setSoutBm(outWmBmStart);
                    trptDayWq.setEoutBm(outWmBmEnd);
                    //用水量 瞬时值 今天第一条减昨天的第一条
                    trptDayWq.setWq(wq.multiply(wqEnd));
                    trptDayWq.setRemainWq(tdataHtWqEnd.getRemainWq());
                    trptDayWq.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    int i = trptDayWqService.insertDayWq(trptDayWq);
                    if (i <= 0) {
                        System.out.println("==========================================================================");
                        System.out.println("房间：" + tdataHtWq.getRoomId() + " 计算失败" + ",日期为：" + LocalDateTime.now());
                        System.out.println("==========================================================================");
                    } else {
                        System.out.println("==========================================================================");
                        System.out.println("房间：" + tdataHtWq.getRoomId() + " 计算成功" + ",日期为：" + LocalDateTime.now());
                        System.out.println("==========================================================================");
                    }
                }
            }
        }
    }
}
